    let currentExam = 'CET4';  // 当前选中的考试类型
    let currentPracticeType = '';  // 当前练习类型
    let currentPracticeSession = {  // 当前练习会话
    questions: [],
    currentIndex: 0,
    score: 0
};

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
    setupEventListeners();
});

    // 设置事件监听器
    function setupEventListeners() {
    // 类型按钮点击事件
    document.querySelectorAll('.type-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.type-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            const type = this.getAttribute('onclick').match(/'(.*?)'/)[1];
            fetchRandomQuestions(type);
        });
    });
}

    async function fetchQuestions(params = {}) {
    try {
    const queryString = new URLSearchParams(params).toString();
    const response = await fetch(`/api/questions?${queryString}`);

    if (!response.ok) {
    throw new Error(`请求失败: ${response.status}`);
}

    return await response.json();
} catch (error) {
    console.error('请求出错:', error);
    throw error;
}
}

    async function fetchRandomQuestions(type) {
    const container = document.getElementById('questions-display');
    container.innerHTML = '<div class="loader"></div>';

    try {
    const params = {};
    if (currentExam !== 'all') params.category = currentExam;
    if (type !== 'all') params.type = type;

    const questions = await fetchQuestions(params);
    displayQuestions(questions);
} catch (error) {
    showError(container, error, () => fetchRandomQuestions(type));
}
}

    function displayQuestions(questions) {
    const container = document.getElementById('questions-display');
    container.innerHTML = '';

    if (!questions || questions.length === 0) {
    container.innerHTML = '<p>暂无相关题目</p>';
    return;
}

    questions.forEach((q) => {
    const element = document.createElement('div');
    element.className = 'question';
    element.dataset.id = q.id;

    element.innerHTML = `
      <h3>${getQuestionTypeName(q.type)} (难度: ${q.difficulty || '未知'})</h3>
      <div class="question-content">${formatContent(q)}</div>
      ${q.analysis ? `<div class="analysis"><strong>解析:</strong> ${q.analysis}</div>` : ''}
    `;

    container.appendChild(element);
});
}

    // 选择考试类型
    function selectExam(examType) {
    currentExam = examType;

    // 更新导航激活状态
    document.querySelectorAll('.nav-category').forEach(item => {
    item.classList.remove('active');
});
    event.currentTarget.classList.add('active');

    // 显示练习类型选择
    document.getElementById('random-questions').style.display = 'none';
    document.getElementById('practice-type-selection').style.display = 'block';
    document.getElementById('practice-mode-selection').style.display = 'none';
    document.getElementById('practice-screen').style.display = 'none';

    // 更新标题
    document.getElementById('exam-title').textContent =
    `${getExamName(examType)} - 选择练习类型`;
}

    // 选择练习类型
    function selectPracticeType(type) {
    currentPracticeType = type;

    document.getElementById('practice-type-selection').style.display = 'none';
    document.getElementById('practice-mode-selection').style.display = 'block';

    document.getElementById('practice-title').textContent =
    `${getQuestionTypeName(type)} - 选择练习模式`;
}

    // 开始练习
    async function startPractice(mode) {
    try {
    const params = {
    category: currentExam,
    type: currentPracticeType
};

    const questions = await fetchQuestions(params);

    if (questions.length === 0) {
    throw new Error('没有找到相关题目');
}

    // 核心逻辑：根据模式处理题目顺序
    currentPracticeSession = {
    questions: mode === 'sequential'
    ? [...questions].sort((a, b) => (a.difficulty || 0) - (b.difficulty || 0)) // 顺序模式按难度升序
    : [...questions].sort(() => Math.random() - 0.5), // 随机模式打乱顺序
    currentIndex: 0,
    score: 0
};

    showPracticeScreen();

} catch (error) {
    const container = document.getElementById('practice-content');
    showError(container, error, () => startPractice(mode));
}
}

    function showPracticeScreen() {
    document.getElementById('practice-mode-selection').style.display = 'none';
    document.getElementById('practice-screen').style.display = 'block';

    const { questions } = currentPracticeSession;
    document.getElementById('current-practice-title').textContent =
    `${getQuestionTypeName(currentPracticeType)}练习 (${questions.length}题)`;

    const submitBtn = document.querySelector('.submit-btn');
    if (submitBtn) {
    submitBtn.style.display = 'block';
    submitBtn.textContent = '提交答案';
    submitBtn.onclick = checkAnswer;
}

    showCurrentQuestion();
}

    function showCurrentQuestion() {
    const { questions, currentIndex } = currentPracticeSession;
    const question = questions[currentIndex];
    const container = document.getElementById('practice-content');

    container.innerHTML = `
    <div class="practice-question" data-id="${question.id}">
        <div class="progress">${currentIndex + 1}/${questions.length}</div>
        <h3>${getQuestionTypeName(question.type)}</h3>
        <div class="question-content">${formatPracticeContent(question)}</div>
        ${renderAnswerArea(question)}
    </div>
    `;

    const submitBtn = document.querySelector('.submit-btn');
    if (submitBtn) {
    submitBtn.style.display = 'block';
    submitBtn.textContent = '提交答案';
    submitBtn.onclick = checkAnswer;
}
}

    async function checkAnswer() {
    const question = currentPracticeSession.questions[currentPracticeSession.currentIndex];
    const userAnswer = getUserAnswer(question.type);

    if (!userAnswer && question.type !== 'writing' && question.type !== 'translation') {
    alert('请选择一个答案');
    return;
}

    const isCorrect = evaluateAnswer(question, userAnswer);
    // 如果回答错误，记录错题
    if (!isCorrect) {
    await recordWrongQuestion(question, userAnswer);
}
    currentPracticeSession.score += isCorrect ? 50 : 10;
    // 显示结果
    showAnswerResult(question, userAnswer, isCorrect);
    // 更新分数和索引
    updateButtonState();
}

    async function recordWrongQuestion(question, userAnswer) {
    try {
    // 获取用户ID - 这里需要根据您的实际用户认证方式调整
    const userId = getUserId();
    if (!userId) {
    throw new Error('无法获取用户信息，请重新登录');
}

    const wrongQuestion = {
    userId: userId,
    questionId: question.id,
    category: currentExam,
    type: question.type,
    questionContent: question.content,
    userAnswer: userAnswer,
    correctAnswer: question.answer,
    analysis: question.analysis,
    wrongCount: 1
};

    const response = await fetch('/api/wrong-questions', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
},
    body: JSON.stringify(wrongQuestion)
});

    if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.message || '记录错题失败');
}

    return await response.json();
} catch (error) {
    console.error('记录错题出错:', error);
    throw error;
}
}

    function updateButtonState() {
    const submitBtn = document.querySelector('.submit-btn');
    if (!submitBtn) return;

    // 确保按钮始终可见
    submitBtn.style.display = 'block';

    if (currentPracticeSession.currentIndex < currentPracticeSession.questions.length - 1) {
    submitBtn.textContent = '下一题';
    submitBtn.onclick = function() {
    currentPracticeSession.currentIndex++;
    showCurrentQuestion();
};
} else {
    submitBtn.textContent = '完成练习';
    submitBtn.onclick = showPracticeResult;
}
}

    function getUserAnswer(questionType) {
    if (questionType === 'reading') {
    let userAnswer = "";
    for (let i = 1; i <= 5; i++) {
    const selected = document.querySelector(`input[name="q${i}"]:checked`);
    userAnswer += selected ? selected.value : "_"; // 用_表示未选
}
    return userAnswer;
}
    return document.querySelector('.answer-area')?.value;
}

    function evaluateAnswer(question, userAnswer) {
    if (!userAnswer || userAnswer.trim().length === 0) {
    return false;
}

    switch (question.type) {
    case 'reading':
    // 阅读理解：精确匹配答案
    return userAnswer === question.answer;

    case 'writing':
    // 写作评估：基于关键词和长度
    return evaluateWriting(question, userAnswer);

    case 'translation':
    // 翻译评估：基于相似度和关键词
    return evaluateTranslation(question, userAnswer);

    default:
    // 其他题型默认检查非空
    return userAnswer.trim().length > 0;
}
}

    function evaluateWriting(question, userAnswer) {
    // 1. 基础检查
    const MIN_WORDS = 3; // 最低字数要求
    const words = userAnswer.split(/\s+/).length;
    if (words < MIN_WORDS) return false;

    // // 2. 关键词检查（如果有参考答案关键词）
    // if (question.keywords && question.keywords.length > 0) {
    //   const requiredKeywords = question.keywords.slice(0, 3); // 取前3个关键关键词
    //   const missingKeywords = requiredKeywords.filter(
    //           kw => !userAnswer.toLowerCase().includes(kw.toLowerCase())
    //   );
    //   if (missingKeywords.length > 1) return false; // 允许漏掉1个关键词
    // }

    // 3. 结构检查（简单版）
    const hasIntro = /(first|首先|开头|begin)/i.test(userAnswer);
    const hasConclusion = /(finally|最后|结尾|conclusion)/i.test(userAnswer);

    return hasIntro && hasConclusion;
}

    function evaluateTranslation(question, userAnswer) {
    // 1. 预处理
    const userText = userAnswer.toLowerCase().replace(/[.,!?;:]/g, '');
    const refText = question.answer.toLowerCase().replace(/[.,!?;:]/g, '');

    // 2. 完全匹配
    if (userText === refText) return true;

    // // 3. 关键词匹配（如果有定义关键词）
    // if (question.keywords) {
    //   const requiredKeywords = question.keywords.slice(0, 3);
    //   const missingKeywords = requiredKeywords.filter(
    //           kw => !userText.includes(kw.toLowerCase())
    //   );
    //   if (missingKeywords.length > 0) return false;
    // }

    // 4. 相似度评估
    const refWords = new Set(refText.split(/\s+/));
    const userWords = new Set(userText.split(/\s+/));

    const intersection = new Set([...refWords].filter(w => userWords.has(w)));
    const similarity = intersection.size / refWords.size;

    return similarity >= 0.7; // 70%单词匹配即算正确
}

    function showAnswerResult(question, userAnswer, isCorrect) {
    let resultHTML = '';

    if (question.type === 'reading') {
    resultHTML = `
        <div class="result ${isCorrect ? 'correct' : 'incorrect'}">
            <h3>${isCorrect ? '✓ 全部正确' : '✗ 有错误'}</h3>
            <div class="answers-comparison">
                <p>您的答案: ${userAnswer}</p>
                <p>正确答案: ${question.answer}</p>
                <div class="analysis">
            <strong>解析:</strong>
            <div class="analysis-content">${question.analysis || '暂无解析'}</div>
        </div>
            </div>
        `;


    resultHTML += `</div>`;
} else {
    // 其他题型保持原有显示方式
    resultHTML = `
        <div class="result ${isCorrect ? 'correct' : 'incorrect'}">
            <h3>${isCorrect ? '✓ 正确' : '✗ 错误'}</h3>
            <div class="correct-answer">
                <strong>正确答案:</strong>
                <div>${question.answer}</div>
            </div>
            <div class="analysis">
            <strong>解析:</strong>
            <div class="analysis-content">${question.analysis || '暂无解析'}</div>
        </div>
        </div>
        `;
}

    document.getElementById('practice-content').insertAdjacentHTML('beforeend', resultHTML);
}

    async function showPracticeResult() {
        const { score, questions } = currentPracticeSession;
        const maxScore = questions.length * 50; // 满分是所有题目都答对的情况
        const percentage = Math.round((score / maxScore) * 100);

        document.getElementById('practice-content').innerHTML = `
    <div class="practice-result">
        <h2>练习完成!</h2>
        <div class="score">得分: ${score}分 (满分${maxScore}分)</div>
        <div class="percentage">得分率: ${percentage}%</div>
        <div class="result-actions">
            <button class="btn-view-ranking" onclick="window.location.href='/ranking.html'">
                查看排行榜
            </button>
        </div>
    </div>
    `;

        try {
            // 确保传递当前用户名
            const currentUsername = getUsername();
            await updateUserScore(currentUsername, score); // 传递用户名和分数
        } catch (error) {
            console.error('更新分数失败:', error);
            alert('分数更新失败: ' + error.message);
        }
        const submitBtn = document.querySelector('.submit-btn');
        if (submitBtn) {
            submitBtn.style.display = 'block';
            submitBtn.textContent = '返回首页';
            submitBtn.onclick = resetPractice;
        }
    }

    async function updateUserScore(username, newScore) {
        try {
            // Convert score to number if it's a string
            const numericScore = typeof newScore === 'string' ?
                parseInt(newScore) : newScore;

            const response = await fetch('/api/updateScore', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    score: numericScore
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || `Server error: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('Error updating score:', {
                error: error.message,
                request: { username, score: newScore }
            });
            throw error;
        }
    }

    function resetPractice() {
    // 重置练习状态
    currentPracticeSession = {
        questions: [],
        currentIndex: 0,
        score: 0
    };

    // 重置UI状态
    document.getElementById('practice-screen').style.display = 'none';
    document.getElementById('practice-mode-selection').style.display = 'none';
    document.getElementById('practice-type-selection').style.display = 'block';

    // 确保按钮状态重置
    const submitBtn = document.querySelector('.submit-btn');
    if (submitBtn) {
    submitBtn.style.display = 'block';
    submitBtn.textContent = '提交答案';
    submitBtn.onclick = checkAnswer;
}
}

    function getQuestionTypeName(type) {
    const typeMap = {
    reading: '阅读理解',
    writing: '写作',
    translation: '翻译'
};
    return typeMap[type] || type;
}

    function getExamName(examType) {
    const examMap = {
    CET4: '大学英语四级',
    CET6: '大学英语六级',
    PE: '考研英语'
};
    return examMap[examType] || examType;
}

    function formatContent(question) {
    switch(question.type) {
    case 'reading':
    return `
        <div class="passage">${question.content}</div>
        <div class="answer">答案: ${question.answer}</div>
        <div class="analysis">解析: ${question.analysis}</div>
      `;
    case 'writing':
    return `
        <div class="prompt">${question.content}</div>
        <div class="answer">参考范文: ${question.answer}</div>
        <div class="analysis">解析: ${question.analysis}</div>
      `;
    case 'translation':
    return `
        <div class="source-text">${question.content}</div>
        <div class="translation">参考译文: ${question.answer}</div>
        <div class="analysis">解析: ${question.analysis}</div>
      `;
    default:
    return `<div>${question.content}</div>`;
}
}

    function formatPracticeContent(question) {
    // 练习时不显示答案
    switch(question.type) {
    case 'reading':
    return `<div class="passage">${question.content}</div>`;
    case 'writing':
    return `<div class="prompt">${question.content}</div>`;
    case 'translation':
    return `<div class="source-text">${question.content}</div>`;
    default:
    return `<div>${question.content}</div>`;
}
}

    function renderAnswerArea(question) {
    switch(question.type) {
    case 'reading':
    let html = '<div class="options-container">';
    for (let i = 1; i <= 5; i++) {
    html += `
                <div class="question-row">
                    <div class="question-number">第${i}题</div>
                    <div class="options-row">
                        ${['A', 'B', 'C', 'D'].map(opt => `
                            <label class="option">
                                <input type="radio" name="q${i}" value="${opt}">
                                <span class="option-letter">${opt}</span>
                            </label>
                        `).join('')}
                    </div>
                </div>
                `;
}
    html += '</div>';
    return html;
    case 'writing':
    return `<textarea class="answer-area" placeholder="请输入你的作文..."></textarea>`;
    case 'translation':
    return `<textarea class="answer-area" placeholder="请输入你的翻译..."></textarea>`;
    default:
    return `<input type="text" class="answer-area" placeholder="请输入你的答案...">`;
}
}

    function showError(container, error, retryCallback) {
    container.innerHTML = `
    <div class="error-message">
      <p>加载失败</p>
      <p>${error.message}</p>
      <button onclick="(${retryCallback.toString()})()">重试</button>
    </div>
  `;
}

    function showMainScreen() {
    currentPracticeSession = {
        questions: [],
        currentIndex: 0,
        score: 0
    };

    const submitBtn = document.querySelector('.submit-btn');
    if (submitBtn) {
    submitBtn.style.display = 'block';
    submitBtn.textContent = '提交答案';
    submitBtn.onclick = checkAnswer;
}
    document.getElementById('practice-screen').style.display = 'none';
    document.getElementById('practice-mode-selection').style.display = 'none';
    document.getElementById('practice-type-selection').style.display = 'block';
    document.getElementById('random-questions').style.display = 'none';
}

    function getUserId() {
    return document.getElementById('userId').value;
}
    function getUsername() {
        return sessionStorage.getItem('username') ||
            (document.getElementById('username') && document.getElementById('username').value) ||
            'unknown';
    }

    window.selectExam = selectExam;
    window.selectPracticeType = selectPracticeType;
    window.startPractice = startPractice;
    window.checkAnswer = checkAnswer;
    window.showMainScreen = showMainScreen;
    window.getDifficultyInfo = getDifficultyInfo;
